package com.waterworld.watch.location.activity;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.waterworld.watch.R;
import com.waterworld.watch.common.activity.BaseActivity;
import com.waterworld.watch.common.bean.CourseBean;
import com.waterworld.watch.common.bean.TrackBean;
import com.waterworld.watch.common.net.BaseObserverListener;
import com.waterworld.watch.common.net.BaseResultBean;
import com.waterworld.watch.common.util.ScreenAdapterUtil;
import com.waterworld.watch.common.util.TimeUtils;
import com.waterworld.watch.location.adapter.TrackAdapter;
import com.waterworld.watch.location.interfaces.ILocationManager;
import com.waterworld.watch.location.manager.LocationManager;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class TrackActivity extends BaseActivity {

    @BindView(R.id.header_parent)
    LinearLayout header_parent;

    @BindView(R.id.header_back)
    ImageView header_back;

    @BindView(R.id.header_title)
    TextView header_title;

    @BindView(R.id.map)
    MapView mMapView;

    @BindView(R.id.iv_previous_day)
    ImageView iv_previous_day;

    @BindView(R.id.tv_track_date)
    TextView tv_track_date;

    @BindView(R.id.iv_after_day)
    ImageView iv_after_day;

    @BindView(R.id.rv_track)
    RecyclerView rv_track;

    @BindView(R.id.rl_no_data)
    RelativeLayout rl_no_data;

    private AMap aMap = null;
    private ILocationManager iLocationManager = LocationManager.getInstance();
    private List<TrackBean> mList = new ArrayList<>();
    private TrackAdapter adapter;

    private BitmapDescriptor bmpTrackPoint;
    private BitmapDescriptor bmpTrackPointStart;
    private BitmapDescriptor bmpTrackPointEndSelected;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_track);
        ButterKnife.bind(this);
        mMapView.onCreate(savedInstanceState);
        if(aMap == null){
            aMap = mMapView.getMap();
        }
        bmpTrackPoint = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.track_point));
        bmpTrackPointStart = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.track_start_point));
        bmpTrackPointEndSelected = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.track_end_point_selected));
        initView();

    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        setViewSize(header_parent, LinearLayout.LayoutParams.MATCH_PARENT, ScreenAdapterUtil.getHeightPx(this)/10);
        header_back.setVisibility(View.VISIBLE);
        header_title.setVisibility(View.VISIBLE);
        header_title.setText(getString(R.string.watch_track));
        tv_track_date.setText(TimeUtils.getDate());

        getTrack(TimeUtils.getDate());

    }

    private void getTrack(String date) {
        if (iLocationManager != null) {
            aMap.clear();
            mList.clear();
            iLocationManager.getTrack(date, new BaseObserverListener<BaseResultBean<TrackBean[]>>() {
                @Override
                public void onCompleted() {
                }

                @Override
                public void onError(Throwable e) {
                    Log.e("nh",e.toString());
                }

                @Override
                public void onNext(BaseResultBean<TrackBean[]> baseResultBean) {
                    if (baseResultBean.getData().length != 0) {
                        rl_no_data.setVisibility(View.GONE);
                        rv_track.setVisibility(View.VISIBLE);
                        mList.addAll(Arrays.asList(baseResultBean.getData()));
                        adapter = new TrackAdapter(TrackActivity.this,mList);
                        rv_track.setLayoutManager(new LinearLayoutManager(TrackActivity.this,LinearLayoutManager.VERTICAL,false));
                        rv_track.setAdapter(adapter);
                        //轨迹以该天最后一次定位为中心
                        LatLng latLng = new LatLng(Double.parseDouble(baseResultBean.getData()[baseResultBean.getData().length-1].getLat()),Double.parseDouble(baseResultBean.getData()[baseResultBean.getData().length-1].getLng()));
                        CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng,15,0,0));
                        aMap.moveCamera(mCameraUpdate);
                        addPointAndLineToMap(baseResultBean.getData());
                    }else {
                        rl_no_data.setVisibility(View.VISIBLE);
                        rv_track.setVisibility(View.GONE);
                    }
                }
            });
        }
    }

    private void addPointAndLineToMap(TrackBean[] beans) {
        List<LatLng> mList = new ArrayList<>();
        if (beans.length == 1) {
            aMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(beans[0].getLat()),Double.parseDouble(beans[0].getLng()))).icon(bmpTrackPointEndSelected).draggable(false));
        } else {
            for (TrackBean bean : beans) {
                mList.add(new LatLng(Double.parseDouble(bean.getLat()),Double.parseDouble(bean.getLng())));
            }
            for (int i=0 ; i<beans.length ; i++) {
                if (i == 0) {
                    aMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(beans[i].getLat()),Double.parseDouble(beans[i].getLng()))).anchor(0.5f,0.5f).icon(bmpTrackPointStart).draggable(false));
                } else if (i == beans.length-1) {
                    aMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(beans[i].getLat()), Double.parseDouble(beans[i].getLng()))).anchor(0.5f,0.5f).icon(bmpTrackPoint).draggable(false));
                    aMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(beans[i].getLat()),Double.parseDouble(beans[i].getLng()))).icon(bmpTrackPointEndSelected).draggable(false));
                }else {
                    aMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(beans[i].getLat()), Double.parseDouble(beans[i].getLng()))).anchor(0.5f,0.5f).icon(bmpTrackPoint).draggable(false));
                }
            }
            PolylineOptions options = new PolylineOptions()
                    .width(15).color(getResources().getColor(R.color.green_1))
                    .addAll(mList);
            aMap.addPolyline(options);
        }
    }

    @OnClick(R.id.header_back)
    void onBack() {
        finish();
    }

    @OnClick(R.id.iv_previous_day)
    void onPreviousDay() {
        getTrack(TimeUtils.getSpecifiedDayBefore(tv_track_date.getText().toString()));
        tv_track_date.setText(TimeUtils.getSpecifiedDayBefore(tv_track_date.getText().toString()));
    }

    @OnClick(R.id.iv_after_day)
    void onAfterDay() {
        getTrack(TimeUtils.getSpecifiedDayAfter(tv_track_date.getText().toString()));
        tv_track_date.setText(TimeUtils.getSpecifiedDayAfter(tv_track_date.getText().toString()));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }
}
